package us.sunrisemorning.mykancolle.social;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;

public class SocialController extends Controller {
    public void rpc() {
        String requestPayload = getRequestPayload(this.getRequest());
        JSONObject request = JSONArray.parseArray(requestPayload).getJSONObject(0);
        String method = request.getString("method");
        String result = "";
        switch (method) {
        case "people.get":
            result = peopleGet(request);
            break;
        case "inspection.create":
            result = inspectionCreate(request);
            break;
        default:
			LogKit.warn("RPC Method Not Found: " + method);
        }
        renderJson(result);
    }

    private String peopleGet(JSONObject request) {
        return "[{\"id\":\"viewer\",\"data\":{\"isOwner\":true,\"isViewer\":true,\"userType\":\"\",\"id\":\"15086600\",\"thumbnailUrl\":\"http:\\/\\/localhost\\/freegame\\/profile\\/m\\/male1\\/male1_mb.gif\",\"displayName\":\"\\u6668\\u66e6\\u7684\\u5fae\\u6dbc\"}}]";
    }
    
    private String inspectionCreate(JSONObject request) {
        // TODO:只有textId参数有价值
        return "[{\"id\":\"key\",\"data\":[{\"textId\":\"1\",\"appId\":\"\",\"authorId\":\"\",\"ownerId\":\"\",\"ctime\":\"2016-06-03T21:20:33\",\"mtime\":\"2016-06-03T21:20:33\",\"status\":0,\"data\":\"\"}]}]";
    }

    private String getRequestPayload(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
        } catch (IOException e) {
            LogKit.error("获取Request的Reader失败", e);
        }
        return sb.toString();
    }
}
